package com.site.wisdom_construction.controller.personnelModule;

import com.alibaba.fastjson.JSONObject;
import com.site.wisdom_construction.Server.WebSocketServer;
import com.site.wisdom_construction.entity.personnelModule.ContractWorkers;
import com.site.wisdom_construction.entity.personnelModule.SafetyTrainingWorkers;
import com.site.wisdom_construction.responseEntity.JsonResult;
import com.site.wisdom_construction.responseEntity.OneDataResult;
import com.site.wisdom_construction.responseEntity.Page;
import com.site.wisdom_construction.responseEntity.PersonData;
import com.site.wisdom_construction.service.integralSupermarketModule.ConversionRecordService;
import com.site.wisdom_construction.service.iotModule.RealTimePersonService;
import com.site.wisdom_construction.service.personnelModule.*;
import com.site.wisdom_construction.service.trainingCheckModule.TrainingCoursesRecordsService;
import com.site.wisdom_construction.util.QrCodeUtils;
import com.site.wisdom_construction.util.TimeUtils;
import com.site.wisdom_construction.util.imgUtil.AliyunOSSUtil;
import com.site.wisdom_construction.util.imgUtil.OssToBase64;
import com.site.wisdom_construction.util.verification.NoToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author daiyifei @Date 2021/12/28 @Description
 */
@Api(tags = "劳务人员接口")
@RestController
@RequestMapping("ContractWorkers")
@CrossOrigin
public class ContractWorkersController {
  @Autowired private ContractWorkersService contractWorkersService;

  @Autowired private SafetyTrainingWorkersService safetyTrainingWorkersService;

  @Autowired private RealTimePersonService realTimePersonService;

  @Autowired private ConversionRecordService conversionRecordService;

  @Autowired private TrainingCoursesRecordsService trainingCoursesRecordsService;

  @Autowired private BadnessWorkersService badnessWorkersService;

  @Autowired private HonorWorkersService honorWorkersService;

  @ApiOperation(value = "下发数据", notes = "测试数据:")
  @PostMapping("/distributedData")
  public JsonResult distributedData(@RequestBody Map map) throws IOException {
    JsonResult jsonResult = new JsonResult();
    OssToBase64 ossToBase64 = new OssToBase64();
    List<Integer> list = (List<Integer>) map.get("list");
    Map mapR = new HashMap();
    int l = 0;
    for (int i = 0; i < list.size(); i++) {
      mapR.put("id", list.get(i));
      ContractWorkers contractWorkers = contractWorkersService.findContractWorkersById(mapR);
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("cmd", "upload person");
      jsonObject.put("id", contractWorkers.getWorkerCard());
      jsonObject.put("name", contractWorkers.getWorkerName());
      jsonObject.put("role", 1);
      jsonObject.put("kind", 0);
      jsonObject.put("term_start", "2021/11/10 12:00:00");
      jsonObject.put("term", "2032/12/18 16:45:30");
      jsonObject.put("reg_image", ossToBase64.getBase64(contractWorkers.getWorkerPicture()));
      WebSocketServer webSocketServer = new WebSocketServer();
      webSocketServer.BroadCastInfo(jsonObject.toJSONString());
      l = l+1;
    }
    if (l >= 1) {
      jsonResult.setCode(200);
      jsonResult.setMessage("成功下发人员信息!");
    } else {
      jsonResult.setCode(20006);
      jsonResult.setMessage("下发人员信息失败!");
    }
    return jsonResult;
  }

  @ApiOperation(value = "增加劳务人员信息", notes = "测试数据:")
  @PostMapping("/insertContractWorkersByMap")
  public JsonResult insertContractWorkersByMap(@RequestBody Map map) throws IOException {
    System.out.println("map:" + map);
    JsonResult jsonResult = new JsonResult();
    JSONObject jsonObject = new JSONObject();
    if (map.get("picture") != null) {
      // 获取现场拍照图片,上传到oss上
      File newFile = new File("/root/personImg/" + (String) map.get("picture"));
      String Host = "faceUpload";
      // 上传到OSS
      String uploadUrl = AliyunOSSUtil.upload(newFile, Host);
      map.put("workerPicture", uploadUrl);

      byte[] data = null;
      try (InputStream in = new FileInputStream("/root/personImg/" + (String) map.get("picture"))) {
        data = new byte[in.available()];
        in.read(data);
      } catch (IOException e) {
        e.printStackTrace();
      }

      jsonObject.put("cmd", "upload person");
      jsonObject.put("id", map.get("workerCard"));
      jsonObject.put("name", map.get("workerName"));
      jsonObject.put("role", 1);
      jsonObject.put("kind", 0);
      jsonObject.put("term_start", "2021/11/10 12:00:00");
      jsonObject.put("term", "2032/12/18 16:45:30");
      jsonObject.put("reg_image", Base64.getEncoder().encodeToString(data));
      // 删除服务器缓存的图片
      newFile.delete();
    }

    int i = contractWorkersService.insertContractWorkersByMap(map);
    if (i == 1) {
      if (map.get("trainStatus").equals("1") && map.get("picture") != null) {
        // 下发数据到设备
        System.out.println("下发数据");
        WebSocketServer webSocketServer = new WebSocketServer();
        webSocketServer.BroadCastInfo(jsonObject.toJSONString());
      }
      jsonResult.setCode(200);
      jsonResult.setMessage("成功录入人员信息!");
    } else {
      jsonResult.setCode(20006);
      jsonResult.setMessage("录入人员信息失败!");
    }
    return jsonResult;
  }

  @ApiOperation(value = "删除劳务人员信息", notes = "测试数据:")
  @PostMapping("/deleteContractWorkers")
  public JsonResult deleteContractWorkers(@RequestBody Map map) {
    JsonResult jsonResult = new JsonResult();
    List<Integer> list = (List<Integer>) map.get("list");
    int l = 0;
    Map mapR = new HashMap();
    for (int i = 0; i < list.size(); i++) {
      mapR.put("id", list.get(i));
      int a = contractWorkersService.deleteContractWorkers(mapR);
      l += a;
    }
    if (l >= 1) {
      jsonResult.setCode(200);
      jsonResult.setMessage("成功删除人员信息!");
    } else {
      jsonResult.setCode(20006);
      jsonResult.setMessage("删除人员信息失败!");
    }
    return jsonResult;
  }

  @ApiOperation(value = "修改劳务人员信息", notes = "测试数据:")
  @PostMapping("/updateContractWorkers")
  public JsonResult updateContractWorkers(@RequestBody Map map) {
    JsonResult jsonResult = new JsonResult();
    map.put("leaveDate", TimeUtils.getNowTime());
    int i = contractWorkersService.updateContractWorkers(map);
    if (i == 1) {
      jsonResult.setCode(200);
      jsonResult.setMessage("成功修改人员信息!");
    } else {
      jsonResult.setCode(20006);
      jsonResult.setMessage("修改人员信息失败!");
    }
    return jsonResult;
  }

  @ApiOperation(value = "劳务人员退场", notes = "测试数据:")
  @PostMapping("/contractWorkersExeunt")
  public JsonResult contractWorkersExeunt(@RequestBody Map map) {
    map.put("leaveDate", TimeUtils.getNowTime());
    JsonResult jsonResult = new JsonResult();
    int i = contractWorkersService.contractWorkersExeunt(map);
    if (i == 1) {
      jsonResult.setCode(200);
      jsonResult.setMessage("劳务人员退场成功!");
    } else {
      jsonResult.setCode(20006);
      jsonResult.setMessage("劳务人员退场失败!");
    }
    return jsonResult;
  }

  @ApiOperation(value = "劳务人员进场", notes = "测试数据:")
  @PostMapping("/contractWorkersCourse")
  public JsonResult contractWorkersCourse(@RequestBody Map map) {
    map.put("entryDate", TimeUtils.getNowTime());
    JsonResult jsonResult = new JsonResult();
    int i = contractWorkersService.contractWorkersCourse(map);
    if (i == 1) {
      jsonResult.setCode(200);
      jsonResult.setMessage("劳务人员进场成功!");
    } else {
      jsonResult.setCode(20006);
      jsonResult.setMessage("劳务人员进场失败!");
    }
    return jsonResult;
  }

  @ApiOperation(value = "分页模糊查询劳务人员信息", notes = "测试数据:")
  @PostMapping("/findContractWorkersByPage")
  public Page findContractWorkersByPage(@RequestBody Map map) {
    Page page = new Page();
    page.setPageNo((Integer) map.get("pageNo"));
    page.setPageSize((Integer) map.get("pageSize"));
    page.setTotal(contractWorkersService.Total(map));
    page.setItems(contractWorkersService.findContractWorkersByPage(map));
    return page;
  }

  @ApiOperation(value = "根据项目id查询所有劳务人员", notes = "测试数据:")
  @PostMapping("/findContractWorkersByProjectId")
  public OneDataResult findContractWorkersByProjectId(@RequestBody Map map) {
    OneDataResult oneDataResult = new OneDataResult();
    oneDataResult.setData(contractWorkersService.findContractWorkersByProjectId(map));
    return oneDataResult;
  }

  @ApiOperation(value = "根据id查询劳务人员信息", notes = "测试数据:")
  @PostMapping("/findContractWorkersById")
  public OneDataResult findContractWorkersById(@RequestBody Map map) {
    OneDataResult oneDataResult = new OneDataResult();
    oneDataResult.setData(contractWorkersService.findContractWorkersById(map));
    return oneDataResult;
  }

  @ApiOperation(value = "人员详情信息", notes = "测试数据:")
  @PostMapping("/findContractWorkersByWorkerId")
  public PersonData findContractWorkersByWorkerId(@RequestBody Map map) {
    PersonData personData = new PersonData();
    ContractWorkers contractWorkers = contractWorkersService.findContractWorkersById(map);
    map.put("workerId",contractWorkers.getId());
    map.put("workersId",contractWorkers.getId());
    map.put("workerCard",contractWorkers.getWorkerCard());
    map.put("workerName",contractWorkers.getWorkerName());
    personData.setBasicInformationData(contractWorkers);
    personData.setSafetyTrainInformationData(safetyTrainingWorkersService.findSafetyTrainingByWorkerId(map));
    personData.setAttendanceInformationData(realTimePersonService.findRealTimePersonByWorkerName(map));
    personData.setConversionInformationData(conversionRecordService.findConversionRecordByWorkersId(map));
    personData.setTrainInformationData(trainingCoursesRecordsService.findTrainingCoursesRecordsByWorkerId(map));
    personData.setBadnessCreditInformationData(badnessWorkersService.findBadnessWorkersByWorkerCard(map));
    personData.setHonorCreditInformationData(honorWorkersService.findHonorWorkersByWorkerCard(map));
    return personData;

  }

  @ApiOperation(value = "导出excel", notes = "")
  @PostMapping("/ExportExcel")
  public void downloadAllClassmate(HttpServletResponse response, @RequestBody Map map) throws IOException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("考勤表");
    List<ContractWorkers> list = contractWorkersService.findContractWorkersByProjectId(map);
    String fileName = "checking-in" + ".xls";
    //新增数据行，并且设置单元格数据

    int rowNum = 1;

    String[] headers = {"姓名", "性别", "身份证号", "手机号", "工种", "班组"};
    //headers表示excel表中第一行的表头

    HSSFRow row = sheet.createRow(0);
    //在excel表中添加表头
    for (int i = 0; i < headers.length; i++) {
      HSSFCell cell = row.createCell(i);
      HSSFRichTextString text = new HSSFRichTextString(headers[i]);
      cell.setCellValue(text);
    }

    //在表中存放查询到的数据放入对应的列
    for (ContractWorkers contractWorkers : list) {
      HSSFRow row1 = sheet.createRow(rowNum);
      row1.createCell(0).setCellValue(contractWorkers.getWorkerName());
      row1.createCell(1).setCellValue(contractWorkers.getWorkerSex());
      row1.createCell(2).setCellValue(contractWorkers.getWorkerCard());
      row1.createCell(3).setCellValue(contractWorkers.getWorkerPhone());
      row1.createCell(4).setCellValue(contractWorkers.getProfessionName());
      row1.createCell(5).setCellValue(contractWorkers.getTeamName());
      rowNum++;
    }

    sheet.autoSizeColumn(0, true);
    sheet.autoSizeColumn(1, true);
    sheet.autoSizeColumn(2, true);
    sheet.autoSizeColumn(3, true);
    sheet.autoSizeColumn(4, true);
    sheet.autoSizeColumn(5, true);
    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    response.flushBuffer();
    workbook.write(response.getOutputStream());
  }

  @ApiOperation(value = "根据id查询劳务人员信息", notes = "测试数据:")
  @PostMapping("/updateWorkerCode")
  @NoToken
  public Integer updateWorkerCode(@RequestBody Map map) {
    List<ContractWorkers> contractWorkersList = contractWorkersService.findContractWorkersByProjectId(map);
    QrCodeUtils qrCodeUtils = new QrCodeUtils();
    int ss = 0;
    for (int i=0;i<contractWorkersList.size();i++){
        ContractWorkers contractWorkers = contractWorkersList.get(i);
        map.put("id",contractWorkers.getId());
        String workerCode = qrCodeUtils.drawingQrCode(map);
        map.put("workerCode",workerCode);
        int sss = contractWorkersService.updateWorkerCode(map);
        ss = ss+sss;
    }
    return ss;
  }
}
